import subprocess as sp
import cv2
import urllib
import json
from holistic import Holistic

process_frame = Holistic().process_frame
response = urllib.request.urlopen("http://localhost:8090/control/get?room=movie")

if response.getcode() == 200:
    key = json.loads(response.read())
else:
    raise "please run livego! code is {}".format(response.getcode())

rtmp_url = "rtmp://localhost:1935/{}/{}".format("live", key.get("data"))
camera_path = 0
cap = cv2.VideoCapture(camera_path)
# Get video information
fps = int(cap.get(cv2.CAP_PROP_FPS))
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# ffmpeg command
command = ['ffmpeg',
           '-y',
           '-f', 'rawvideo',
           '-vcodec', 'rawvideo',
           '-pix_fmt', 'bgr24',
           '-s', "{}x{}".format(width, height),
           '-r', str(fps),
           '-i', '-',
           '-c:v', 'libx264',
           '-pix_fmt', 'yuv420p',
           '-preset', 'ultrafast',
           '-f', 'flv',
           rtmp_url]
# 管道配置
p = sp.Popen(command, stdin=sp.PIPE)

while (cap.isOpened()):
    ret, frame = cap.read()
    if not ret:
        print("Opening camera is failed")
        break

    frame = process_frame(frame)

    # write to pipe
    p.stdin.write(frame.tobytes())  # tobytes 将参数使用UTF-8的编码格式转换成byte[]
